<template>
  <div>
    <button @click="triggerUpload" :disabled="isUploading">
      <span v-if="isUploading">上传中</span>
      <span v-else>上传文件</span>
    </button>
    <input
      type="file"
      :style="{ display: 'none' }"
      ref="fileInput"
      @change="handleFileChange"
      multiple="multiple"
    />
    <ul class="upload-list">
      <li :class="`uploaded-file upload-${item.status}`"  v-for="item in uploadedFiles" :key="item.id">
        {{ item.name }}
        <span v-if="item.status === 'loading'" class="file-icon"><LoadingOutlined/></span>
        <span v-else class="file-icon"><FileOutlined/></span>
        <span class="filename">{{item.name}}</span>
        <span class="delete-icon" @click="removeFile(item.id)"><DeleteOutlined/></span>
      </li>
    </ul>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, computed, reactive } from "vue";
import { DeleteOutlined, LoadingOutlined, FileOutlined } from '@ant-design/icons-vue'
import { v4 as uuidv4 } from "uuid";
import { last } from "lodash-es";
import axios from "axios";
import component from "*.vue";
type UploadStaus = "ready" | "loading" | "success" | "error";
export interface UploadFile {
  id: string;
  size: number;
  name: string;
  status: UploadStaus;
  raw: File;
  resp?: any;
}
export default defineComponent({
  name: "up-file",
  props: {},
  components: {
    DeleteOutlined,
    LoadingOutlined,
    FileOutlined
  },
  setup(props, context) {
    const fileInput = ref<null | HTMLInputElement>(null);
    const uploadedFiles = ref<UploadFile[]>([]);
    const isUploading = computed(() => {
      return uploadedFiles.value.some((file) => file.status === "loading"); //some方法只要一个是TRUE就是返回，与every相反
    });
    const triggerUpload = () => {
      if (fileInput.value) {
        fileInput.value.click();
      }
    };
    const handleFileChange = (e: Event) => {
      const target = e.target as HTMLInputElement;
      const files = target.files;
      if (files) {
        const filesLength = files.length;
        for (let i = 0; i < filesLength; i++) {
          const uploadedFile = files[i];
          const formData = new FormData();
          formData.append("file", uploadedFile);
          const fileObj = reactive<UploadFile>({
            id: uuidv4(),
            size: uploadedFile.size,
            name: uploadedFile.name,
            status: "loading",
            raw: uploadedFile,
          });
          uploadedFiles.value.push(fileObj);
          axios
            .post("http://localhost:7002/tools/saveavatar", formData, {
              headers: {
                "Content-Type": "multipart/form-data",
              },
            })
            .then((resp: any) => {
              //这是上传成功状态
              fileObj.status = "success";
            })
            .catch(() => {
              //上传失败状态
              fileObj.status = "error";
            })
            .finally(() => {
              if (fileInput.value && filesLength - 1 === i) {
                fileInput.value.value = "";
              }
            });
        }
      }
    };
    const removeFile = (id: any)=>{
      uploadedFiles.value = uploadedFiles.value.filter(file=>file.id!==id)
    }
    return {
      triggerUpload,
      fileInput,
      handleFileChange,
      isUploading,
      uploadedFiles,
      removeFile
    };
  },
});
</script>
<style lang="scss">
.upload-list {
  margin: 0;
  padding: 0;
  list-style-type: none;
}
.upload-list li {
  transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
  font-size: 14px;
  line-height: 1.8;
  margin-top: 5px;
  box-sizing: border-box;
  border-radius: 4px;
  min-width: 200px;
  position: relative;
  &:first-child {
    margin-top: 10px;
  }
  .file-icon {
    svg {
      margin-right: 5px;
      color: rgba(0, 0, 0, 0.45);
    }
  }
  .filename {
    margin-left: 5px;
    margin-right: 40px;
  }
  &.upload-error {
    color: #f5222d;
    svg {
      color: #f5222d;
    }
  }
  .file-status {
    display: block;
    position: absolute;
    right: 5px;
    top: 0;
    line-height: inherit;
  }
  .delete-icon {
    display: none;
    position: absolute;
    right: 7px;
    top: 0;
    line-height: inherit;
    cursor: pointer;
  }
  &:hover {
    background-color: #efefef;
    .file-status {
      display: none;
    }
    .delete-icon {
      display: block;
    }
  }
}
</style>
